import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import request from "../../utils/request";
import type {
  DemoState,
  BannerItem,
  LoadingStatus,
  ApiResponse,
} from "../../type/store";

// 定义异步action creator
export const fetchUserData = createAsyncThunk(
  "dome/fetchUserData",
  async (): Promise<BannerItem[]> => {
    try {
      const response = await request.get<ApiResponse<BannerItem[]>>(
        `/api/health/share/v1/bannersShow`
      );
      return response.data.result || response.data.data || [];
    } catch (error: any) {
      return Promise.reject(error.message || "获取轮播图数据失败");
    }
  }
);

const initialState: DemoState = {
  count: 1,
  userData: null,
  status: "idle",
  error: "",
  bannderList: [],
};

const DomeSlice = createSlice({
  name: "dome",
  initialState,
  reducers: {
    addCart(state, action: PayloadAction<number>) {
      state.count += action.payload;
    },
    hadelCount(state) {
      state.count -= 1;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserData.pending, (state) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(fetchUserData.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.bannderList = action.payload;
      })
      .addCase(fetchUserData.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.error.message || "获取数据失败";
      });
  },
});

export const { addCart,hadelCount } = DomeSlice.actions;
export default DomeSlice.reducer;
